package com.hevery.security.core.validate.code;

import com.hevery.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: zhy
 * @description: 继承OncePerRequestFilter过滤器保证每次只能被调用一次；
 * 实现接口InitializingBean是Spring初始化bean的一种方式，在Spring初始化ValidateCodeFilter的时候会自动调用重写的afterPropertiesSet的方法。
 * @date: created on 2017/11/06
 * @modified by: 该模块在重构完成之后已经废弃，不在使用
 */
@Deprecated
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean{


    private AuthenticationFailureHandler authenticationFailureHandler;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**用来存储当前拦截的url*/
    private Set<String> urls = new HashSet<>();

    private SecurityProperties securityProperties;

    private AntPathMatcher pathMatcher = new AntPathMatcher();


    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getCode().getSms().getUrl(), ",");
        if(configUrls != null){
            for (String configUrl : configUrls) {
                urls.add(configUrl);
            }
        }
        //登录请求也必须进行验证码校验
        urls.add("/authentication/mobile");
    }

    /**
     * 对验证码进行校验，如果成功则执行下一个UsernamePasswordAuthenticationFilter过滤器；如果失败则调用自定义错误处理器AuthenticationFailureHandler返回错误信息
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        boolean action = false;
        //比如说urls={"/user","/user/*"}，而request.getRequestURI()是user/1，按道理应该对请求中的url进行验证码的校验
        //所以这个时候通过equals进行判断是不可取的，所以我们可以通过Spring中的一个工具类AntPathMatcher来进行正则匹配的判断。
        for (String url : urls){
            if(pathMatcher.match(url, request.getRequestURI())){
                action = true;
            }
        }
        //如果是登录请求，并且请求的方法是post则进行处理
//        if(StringUtils.equals("/authentication/form", request.getRequestURI()) && StringUtils.equalsIgnoreCase(request.getMethod(), "post")){
          if(action){
            try {
                validate(new ServletWebRequest(request));
            }catch (ValidateCodeException e){
                //如果捕获到异常，则用之前自定义的错误处理器来处理异常发霉JSON格式的信息或者跳转页面；注意：失败处理完之后一定要直接返回，不能执行下面的doFilter方法
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {

        //获取Session中存入的验证码的值
        ValidateCode codeInSession = (ValidateCode) sessionStrategy.getAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX + "SMS");

        //获取请求中传来的验证码的值
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode");

        if(StringUtils.isBlank(codeInRequest)){
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if(codeInSession == null){
            throw new ValidateCodeException("验证码不存在");
        }

        //如果已经过期，将当前验证码从Session中移除掉
        if(codeInSession.isExpired()){
            sessionStrategy.removeAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX + "SMS");
            throw new ValidateCodeException("验证码已过期");
        }
        if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)){
            throw new ValidateCodeException("验证码不匹配");
        }
        //验证码验证成功，将已经验证成功的验证码从Session中移出
        sessionStrategy.removeAttribute(request, ValidateCodeProcessor.SESSION_KEY_PREFIX + "SMS");
    }

    public AuthenticationFailureHandler getAuthenticationFailureHandler() {
        return authenticationFailureHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    public SessionStrategy getSessionStrategy() {
        return sessionStrategy;
    }

    public void setSessionStrategy(SessionStrategy sessionStrategy) {
        this.sessionStrategy = sessionStrategy;
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
